package mi.payment.controller;

import android.annotation.SuppressLint;

import mi.payment.R;
import mi.payment.bean.db.TradeData;
import mi.payment.constants.BaseErrorCode;
import mi.payment.constants.Params;
import mi.payment.db.dao.PayDetail;
import mi.payment.settings.SignOperation;
import mi.payment.ui.base.ParentActivity;
import mi.payment.ui.other.LoginActivity;
import mi.payment.utils.datacollection.PayDetailCollection;
import mi.payment.utils.transaction.ParamsInitTask;
import mi.payment.utils.transaction.SignOutTask;
import sunmi.payment.L3.L3BroadcastHelper;
import sunmi.payment.L3.L3ErrorCode;
import sunmi.payment.ui.dialog.LoadDialog;

/**
 * 签退
 *
 * @author tomcat on 2017/4/28.
 */

public class SignOutCtrl extends BaseController {

    public SignOutCtrl(ParentActivity activity) {
        super(activity);
    }

    /**
     * 签退
     */
    public void signOut() {
        TradeData tradeData = Params.newTradeData();
        @SuppressLint("StaticFieldLeak")
        SignOutTask task = new SignOutTask(activity) {

            @Override
            protected void onPostExecuteImpl(TradeData tradeData) {
                PayDetail payDetail = tradeData.getPayDetail();
                String msg;
                String answerCode = payDetail.getTradeAnswerCode();
                if (answerCode.equals("00")) {
                    msg = activity.getString(R.string.sign_out_success);
                } else {
                    msg = BaseErrorCode.getCode(answerCode);
                }
                if (Params.sL3Params != null) {
                    L3BroadcastHelper.sendResultBroadcast(activity, answerCode.equals("00"), L3ErrorCode.ERROR_TRADE_FAILED, payDetail);
                } else {
                    activity.showToast(msg);
                    LoginActivity.startAction(activity, true);
                }

                // 清除当前的签到时间
                SignOperation.getInstance().saveLastSignTime(0);
                // 重置是否已经签到的标志位
                ParamsInitTask.isChecked = false;

                // 上送数据给dataService
                PayDetailCollection.getInstance().setSignOut(true);
                PayDetailCollection.getInstance().uploadData(payDetail);

                activity.finish();
            }

        };
        LoadDialog dialog = activity.getLoadingDialog(R.string.sign_out);
        task.setLoadDialog(dialog);
        task.execute(tradeData);
    }

}
